package com.hehe.controller;

import com.hehe.entity.ResponseObj;
import com.hehe.entity.User;
import com.hehe.service.UserService;
import com.hehe.util.FileUtil;
import com.hehe.util.GsonUtil;
import com.hehe.util.IsUserLogin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.List;

@Controller
public class UserController {
    @Autowired
    private UserService userService;
    private ResponseObj responseObj;


    @RequestMapping(value = "/reg")
    public String register(String username,String nickname,String password1,String password2,HttpServletRequest  req){
        System.out.println("注册中....");

        try {
            req. setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println(username+nickname+password1+password2);
        if(username!=null && password1!=null && password2!=null) {
            if (userService.findOneByname(username) != null) {

                System.out.println("该用户已存在");
                req.setAttribute("reg_msg", "该用户已存在");
                return "normal/register";


            } else if (! password1 .equals(password2) ) {
                System.out.println("密码不一致");
                req.setAttribute("reg_msg", "密码不一致");
                return "normal/register";

            } else {
                User user = new User();
                user.setUsername(username);
                user.setNickname(nickname);
                user.setPassword(password1);
                int result = userService.add(user);
                req.setAttribute("reg_msg", "注册成功");
                return "normal/login";

            }
        }
        return "normal/register";
    }



    @RequestMapping(value = "/login")
    public String login(String username,String password,Boolean rememberme,HttpServletRequest req){
        try {
            req.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println("登录中。。。");
        if(username==null){
            return "normal/login";
        }
        if(username.equals("admin")&& password.equals("admin")){
            System.out.println("管理员登录");
            return "redirect:UserManager";
        }

        User user = userService.findOneByname(username);

        if (user == null){
            req.setAttribute("login_msg","该用户不存在！");
            return "normal/login";
        }else if(! user.getPassword().equals(password)){
            req.setAttribute("login_msg","密码错误！");
            return "normal/login";
        }else if(user.getStatus()==0){
            req.setAttribute("login_msg","该用户已被禁用，请于管理员联系！");
            return "normal/login";
        } else{
            System.out.println("名字"+user.getUsername());
            HttpSession session = req.getSession();
            session.setAttribute("user",user);
            System.out.println("执行");
            return "forward:";
        }

    }


    //个人中心
    @RequestMapping(value = "/personal")
    public ModelAndView personal(HttpSession session){
        User user = (User) session.getAttribute("user");

        IsUserLogin is = new IsUserLogin(session);
        if( is.IsLogin().equals("no")){
            ModelAndView mav = new ModelAndView("normal/login");
            return mav;
        }else{
            ModelAndView mav = new ModelAndView("redirect:MyCenter?userid="+ user.getUserid());
            return mav;
        }

    }

    //修改密码
    @RequestMapping(value = "/ModifyPass")
    public String ModifyPass(@RequestParam("oldpass") String oldpass,
                             @RequestParam("newpass") String newpass,HttpServletRequest req){

        User user = (User) req.getSession().getAttribute("user");
        if(user.getPassword().equals( oldpass)){
            System.out.println("密码匹配");
            user.setPassword(newpass);
            int i = userService.update(user);
            if(i>0) {
                //修改成功，重新登录
                req.setAttribute("login_msg","修改密码成功，请重新登录");
                return "normal/login";
            }else{
                return "normal/personal";
            }
        }else{
            req.setAttribute("pass_msg","原始密码错误");
            System.out.println("密码不匹配");
            return "normal/personal";
        }

    }


    //修改昵称
    @RequestMapping(value = "/ModifyNickname")
    public String ModifyUsername(@RequestParam String name,HttpServletRequest req){
        User user = (User) req.getSession().getAttribute("user");
        user.setNickname(name);
        int re = userService.update_nickname(user);

        return "normal/personal";

    }


    //我们在UserController这个控制器里添加这个方法
    @RequestMapping(value = "/uploadHeadPic", method = RequestMethod.POST
            , produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object uploadHeadPic(@RequestParam("upload") MultipartFile file, HttpServletRequest request) {
        //在这里面文件存储的方案一般是：收到文件→获取文件名→在本地存储目录建立防重名文件→写入文件→返回成功信息
        //如果上面的步骤中在结束前任意一步失败，那就直接失败了。
        FileOutputStream out=null;

        System.out.println("执行0==========");
        if (null == file || file.isEmpty()) {
            responseObj = new ResponseObj();
            responseObj.setCode(400);
            responseObj.setMsg("文件不能为空");

        }else{

            System.out.println("执行1==========");
            responseObj = new ResponseObj();

            User user = (User) request.getSession().getAttribute("user");
            String url = new FileUtil().createImgDir("User_Img",user.getUserid());
            try {
                byte[] f = file.getBytes();
                String filename = file.getOriginalFilename();
                out = new FileOutputStream(url+filename);
                out.write(f);

                //存入数据库
                user.setHeadPic(filename);
                userService.update_headpic(user);


                responseObj.setCode(200);
                responseObj.setMsg(file.getOriginalFilename());

            } catch (IOException e) {
                System.out.println("上传失败");
                responseObj.setCode(500);
                responseObj.setMsg("文件保存失败");
            }finally {
                // 完毕，关闭所有链接
                try {
                    out.close();
                } catch (IOException e) {
                    System.out.println("关闭流失败");
                }
            }

        }

        return new GsonUtil().CollectionToJson(responseObj);
    }

    @RequestMapping(value = "/showHeadPic")
    public void findPicFromDisk(HttpServletRequest request,HttpServletResponse response ){
        String url=null;
        User user = (User)request.getSession().getAttribute("user");
        String pic = user.getHeadPic();
        if (pic == null){
            System.out.println("======头像路径为空");

        }else {

            url = new FileUtil().getFileUrl() + "User_Img\\"
                    + user.getUserid() + "\\" + user.getHeadPic();

            System.out.println("============" + url);

            try {
                //图片读取路径
                FileInputStream in = new FileInputStream(url);
                int i = in.available();
                byte[] data = new byte[i];
                in.read(data);
                in.close();

                //写图片
                OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
                outputStream.write(data);
                outputStream.flush();
                outputStream.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }

    /**
     * 退出登录
     */
    @RequestMapping("/logout")
    public ModelAndView logout(HttpSession session){
        session.removeAttribute("user");
        ModelAndView mav = new ModelAndView();
        mav.setViewName("redirect:login");
        return mav;
    }



}
